package com.spark.trouble

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.alert
import com.spark.common.ext.report
import com.spark.common.ext.success
import com.spark.common.ext.wrapIO
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import kotlinx.android.synthetic.main.frag_resp_content.*

/**
 * [待办] 重大治理任务 -> 待审核
 */
@SuppressLint("CheckResult")
class ResponsbleContentFragment : BaseFragment() {
    private var taskId: String = ""
    private lateinit var rspContentAdapter: RSPContentAdapter

    companion object {
        fun newInstance(taskId: String): ResponsbleContentFragment {
            val target = ResponsbleContentFragment()
            val args = Bundle()
            args.putString("taskId", taskId)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_resp_content
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            getString("taskId")?.apply {
                this@ResponsbleContentFragment.taskId = this
                fetchInfo(taskId)
            }
        }
        // 驳回
        tv_reject.setOnClickListener {
            activity?.apply {
                RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                        .affirm { d, str ->
                            if (str.isNullOrBlank()) {
                                alert("请输入驳回理由")
                            } else {
                                d.dismiss()
                                submitReject(this@ResponsbleContentFragment.taskId, str!!)
                            }
                        }
                        .cancel { d, i ->
                            d.dismiss()
                        }
                        .create()
                        .show()
            }
        }
        // 通过
        btn_resolve.setOnClickListener { submitResolve(this@ResponsbleContentFragment.taskId) }

        rspContentAdapter = RSPContentAdapter(R.layout.item_resp_content)
        recy_resp_contents.apply {
            adapter = rspContentAdapter
            layoutManager = LinearLayoutManager(context)
        }
    }

    private fun fetchInfo(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agencty_major_fetch_verify}", mutableMapOf("taskId" to taskId).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                            val gson = Gson()
                            gson.fromJson(it, MajorAgencyInfoModel::class.java)?.apply {
                                if (code == "200" && resultMaps.isNotEmpty()) {
                                    resultMaps[0].apply {
                                        gson.fromJson(this.responsible_remark, RSPItemModel::class.java)?.apply {
                                            rspContentAdapter.addData(this)
                                        }
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }

    /**
     * [待办] 待审核 -> 通过
     */
    @SuppressLint("CheckResult")
    private fun submitResolve(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_major_submit_verify}", mutableMapOf("taskId" to taskId, "approveState" to "2").toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )

    }

    @SuppressLint("CheckResult")
    private fun submitReject(taskId: String, reason: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_alltask_submit_reject2_verify_confirm}", mutableMapOf("taskId" to taskId, "refuseReason" to reason).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中")
                        }
                )
    }

}


class RSPContentAdapter(layoutRes: Int) : BaseQuickAdapter<RSPItemModel, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: RSPItemModel?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_unit, item.departmentName)
            setText(R.id.tv_resp_man, "责任人: ${item.userName}")
            setText(R.id.tv_leader, "领导：${item.leaderName}")
            setText(R.id.expandable_text, item.remark)
            setText(R.id.tv_lost_point, "罚: ${item.score}分")
            setText(R.id.tv_fine, "扣：${item.money}元")
        }
    }

}


data class RSPItemModel(
        var score: String = "", // 0
        var money: String = "", // 0
        var remark: String = "", //  隐患升级
        var departmentId: String = "", // 25
        var departmentName: String = "", // 通风安全科
        var leaderId: String = "", // 21
        var leaderName: String = "", // 闫老师
        var userId: String = "", // 20
        var userName: String = "" // 袁建
)